#include "include/swei_imme_loc.h"
#include "include/swei_cmd.h"
#include "global.h"
#include "include/port/swei_log.h"
#include "service/include/swei_downlink.h"
#include "misc/misc_api.h"
#include "gnss_power_mgr.h"
#include "gnss_request.h"

__weak void swei_location_push_gps_fast(void)
{
    log_d("fix ok, immediately generate gps report\r\n ");
#warning "need to implement API interfaces"
}

__weak void swei_location_push_lbs_fast(void)
{
    log_d("fix invaild, immediately generate lbs report\r\n ");
#warning "need to implement API interfaces"
}


/**
 * @brief GNSS 定位请求执行完成回调事件
 */
static void imme_location_req_callback(void *data, size_t size)
{
    struct fix_info *info = NULL;

    if (size != sizeof(struct fix_info))
        goto lbs;

    info = (struct fix_info*)data;
    if (FIX_OK == info->state) {         /* 请求定位成功, 则上报GPS报文 */
        swei_location_push_gps_fast();
        return;
    }

lbs:
    /* 定位失败, 则产生wifi和lbs报文 */
    swei_location_push_lbs_fast();
}

/**
 * @brief 立即定位操作回调
 * @param  cmd_id           My Param doc
 * @param  cmd_opcode       My Param doc
 * @param  p_data           My Param doc
 * @param  data_len         My Param doc
 * @return DLCMD_RET_TYPE_ENUM
 */
static DLCMD_RET_TYPE_ENUM imme_location_event_callback(DOWN_LINK_CMD_ENUM cmd_id, uint16_t cmd_opcode, const unsigned char *p_data, uint32_t data_len)
{
    /* 当前无定位, 请求GNSS定位 */
    if (FIX_OK != is_gnss_fixed(NULL)) {
        gnssmgr_request_register(GNSSMGR_FIX_REQUEST, imme_location_req_callback);
    }
    else {
        /* 立刻产生GPS报文 */
        swei_location_push_gps_fast();
    }
    return DLCMD_RET_FINISH;
}

/**
 * @brief 立即定位功能初始化
 */
void swei_imme_location_init(void)
{
    swei_downlink_cmd_register(DOWN_LINK_CMD_IMMEDIATELY_LOCATE, imme_location_event_callback);
}
